<?php
if (!file_exists('../install.lock')) {
    header('Location: ../install.php');
    exit;
}
session_start();
require_once '../config.php';

// 检查是否登录
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}



// 获取系统设置
$settings = getSettings();

$error = '';
$success = '';

// 处理卡密操作
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    // 处理单个操作
    $kami_id = intval($_POST['kami_id'] ?? 0);
    
    if ($kami_id > 0) {
        try {
            switch ($action) {
                case 'delete':
                    $stmt = $pdo->prepare("DELETE FROM kami WHERE id = ?");
                    $stmt->execute([$kami_id]);
                    $_SESSION['success'] = '卡密已删除';
                    break;
                    
                case 'toggle_status':
                    $stmt = $pdo->prepare("UPDATE kami SET status = 1 - status WHERE id = ?");
                    $stmt->execute([$kami_id]);
                    $_SESSION['success'] = '卡密状态已更新';
                    break;
            }
            // 重定向到当前页面，避免刷新重复提交
            header('Location: ' . $_SERVER['PHP_SELF'] . '?' . http_build_query($_GET));
            exit;
        } catch (PDOException $e) {
            $_SESSION['error'] = '操作失败：' . $e->getMessage();
            header('Location: ' . $_SERVER['PHP_SELF'] . '?' . http_build_query($_GET));
            exit;
        }
    }

    // 处理批量删除请求
    if ($_SERVER['REQUEST_METHOD'] === 'POST'  && !empty($_POST['kami_ids']) && isset($_POST['batch_delete'])) {
        $kami_ids = $_POST['kami_ids'];
        if (!is_array($kami_ids)) $kami_ids = [$kami_ids];
        if (count($kami_ids) > 0) {
            $in = str_repeat('?,', count($kami_ids) - 1) . '?';
            $stmt = $pdo->prepare("DELETE FROM kami WHERE id IN ($in)");
            $stmt->execute($kami_ids);
            $_SESSION['success'] = '批量删除成功';
            header('Location: kami_manage.php');
            exit;
        }
    }
}

// 获取会话消息
$error = $_SESSION['error'] ?? '';
$success = $_SESSION['success'] ?? '';
unset($_SESSION['error'], $_SESSION['success']);

// 获取筛选参数
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';
$type_filter = $_GET['type_filter'] ?? '';
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

// 构建查询条件
$where = [];
$params = [];

if (!empty($search)) {
    $where[] = "kami_key LIKE ?";
    $params[] = "%{$search}%";
}

if (!empty($type_filter)) {
    $where[] = "type = ?";
    $params[] = $type_filter;
}

if ($status !== '') {
    if ($status === 'expired') {
        $where[] = "first_use_time IS NOT NULL AND expire_time IS NOT NULL AND expire_time < NOW()";
    } elseif ($status === '1') { // 未使用
        $where[] = "status = 1 AND (expire_time IS NULL OR expire_time >= NOW()) AND use_count = 0";
    } elseif ($status === '0') { // 已使用
        $where[] = "use_count > 0";
    } elseif ($status === '2') { // 已禁用
        $where[] = "status = 0";
    }
}

$whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

// 获取总记录数
$stmt = $pdo->prepare("SELECT COUNT(*) FROM kami $whereClause");
$stmt->execute($params);
$total = $stmt->fetchColumn();
$total_pages = ceil($total / $per_page);

// 获取分页数据
$stmt = $pdo->prepare("
    SELECT k.*, 
           CASE 
               WHEN k.type = '分钟卡' THEN SUBSTRING_INDEX(k.expire_time, ' ', -1) 
               WHEN k.type = '小时卡' THEN SUBSTRING_INDEX(k.expire_time, ' ', -1)
               WHEN k.type = '天卡' THEN SUBSTRING_INDEX(k.expire_time, ' ', -1)
               WHEN k.type = '周卡' THEN SUBSTRING_INDEX(k.expire_time, ' ', -1)
               WHEN k.type = '月卡' THEN SUBSTRING_INDEX(k.expire_time, ' ', -1)
               WHEN k.type = '季卡' THEN SUBSTRING_INDEX(k.expire_time, ' ', -1)
               WHEN k.type = '年卡' THEN SUBSTRING_INDEX(k.expire_time, ' ', -1)
               WHEN k.type = '永久卡' THEN '永久'
               ELSE '-' 
           END as duration_info
    FROM kami k
    $whereClause 
    ORDER BY create_time DESC 
    LIMIT $offset, $per_page
");
$stmt->execute($params);
$cards = $stmt->fetchAll();

// 获取所有卡密类型用于筛选下拉框
$types = $pdo->query("SELECT DISTINCT type FROM kami ORDER BY type")->fetchAll(PDO::FETCH_COLUMN);

?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title><?php echo htmlspecialchars($settings['title']); ?> - 卡密管理</title>
    <link rel="shortcut icon" type="image/x-icon" href="../assets/favicon.ico">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-touch-fullscreen" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <link rel="stylesheet" type="text/css" href="../assets/css/materialdesignicons.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/animate.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/style.min.css">
    <style>
        /* 移动端表格优化 */
        @media (max-width: 767.98px) {
            .table-responsive {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }
            
            .table-nowrap th, 
            .table-nowrap td {
                white-space: nowrap;
            }
            
            /* 表格内容紧凑显示 */
            .table-sm th, 
            .table-sm td {
                padding: 0.3rem;
                font-size: 0.875rem;
            }
            
            /* 确保水平滚动条可见 */
            .table-responsive-sm {
                position: relative;
            }
            
            /* 移动端分页紧凑显示 */
            .pagination .page-item {
                margin: 0 1px;
            }
            
            .pagination .page-link {
                padding: 0.4rem 0.6rem;
                min-width: 32px;
                text-align: center;
                font-size: 0.875rem;
            }
        }
        
        /* 复制按钮样式 */
        .copy-btn {
            cursor: pointer;
            color: #3f6ad8;
            margin-left: 5px;
        }
        
        .copy-btn:hover {
            color: #2952a3;
        }
        
        @media (max-width: 767.98px) {
            .table-kami-mobile {
                display: block;
                width: 100%;
            }
            .table-kami-mobile thead { display: none; }
            .table-kami-mobile tbody { display: block; }
            .table-kami-mobile tr { display: block; margin-bottom: 1rem; border: 1px solid #eee; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.03); background: #fff; }
            .table-kami-mobile td { display: flex; width: 100%; border: none; border-bottom: 1px solid #f2f2f2; align-items: center; padding: 0.5rem 1rem; font-size: 15px; }
            .table-kami-mobile td:last-child { border-bottom: none; }
            .table-kami-mobile .kami-label { min-width: 80px; color: #888; font-size: 13px; margin-right: 8px; display: inline-block; }
            .table-kami-mobile .kami-actions { justify-content: flex-end; }
        }
        @media (min-width: 768px) {
            .table-kami-mobile .kami-label { display: none !important; }
        }
    </style>
</head>

<body>
<!--页面loading-->
<div id="lyear-preloader" class="loading">
    <div class="ctn-preloader">
        <div class="round_spinner">
            <div class="spinner"></div>
            <img src="../assets/images/loading-logo.png" alt="">
        </div>
    </div>
</div>
<!--页面loading end-->

<div class="lyear-layout-web">
    <div class="lyear-layout-container">
        <?php $current_page = 'kami_manage'; include 'navbar.php'; ?>
        
        <!--页面主要内容-->
        <main class="lyear-layout-content">
            <div class="container-fluid p-t-15">
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-header">
                                <h4>卡密管理</h4>
                            </div>
                            <div class="card-toolbar">
                                <form class="search-bar" method="get">
                                    <div class="row">
                                        <div class="col-md-4 mb-3">
                                            <div class="input-group">
                                                <span class="input-group-text">搜索</span>
                                                <input type="text" class="form-control" name="search" placeholder="输入卡密关键字" value="<?php echo htmlspecialchars($search); ?>">
                                            </div>
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <div class="input-group">
                                                <span class="input-group-text">状态</span>
                                                <select class="form-control" name="status">
                                                    <option value="">全部状态</option>
                                                    <option value="1" <?php echo $status === '1' ? 'selected' : ''; ?>>未使用</option>
                                                    <option value="0" <?php echo $status === '0' ? 'selected' : ''; ?>>已使用</option>
                                                    <option value="expired" <?php echo $status === 'expired' ? 'selected' : ''; ?>>已过期</option>
                                                    <option value="2" <?php echo $status === '2' ? 'selected' : ''; ?>>已禁用</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <div class="input-group">
                                                <span class="input-group-text">类型</span>
                                                <select class="form-control" name="type_filter">
                                                    <option value="">全部类型</option>
                                                    <option value="分钟卡" <?php if($type_filter=="分钟卡") echo 'selected'; ?>>分钟卡</option>
                                                    <option value="小时卡" <?php if($type_filter=="小时卡") echo 'selected'; ?>>小时卡</option>
                                                    <option value="天卡" <?php if($type_filter=="天卡") echo 'selected'; ?>>天卡</option>
                                                    <option value="周卡" <?php if($type_filter=="周卡") echo 'selected'; ?>>周卡</option>
                                                    <option value="月卡" <?php if($type_filter=="月卡") echo 'selected'; ?>>月卡</option>
                                                    <option value="季卡" <?php if($type_filter=="季卡") echo 'selected'; ?>>季卡</option>
                                                    <option value="年卡" <?php if($type_filter=="年卡") echo 'selected'; ?>>年卡</option>
                                                    <option value="永久卡" <?php if($type_filter=="永久卡") echo 'selected'; ?>>永久卡</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-2 mb-3">
                                            <button class="btn btn-primary w-100" type="submit">搜索</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                            <div class="card-body">
                                <?php if ($error): ?>
                                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                        <strong>错误！</strong> <?php echo $error; ?>
                                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if ($success): ?>
                                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                                        <strong>成功！</strong> <?php echo $success; ?>
                                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="table-responsive">
                                    <form id="batch-kami-form" method="post" action="" onsubmit="return checkBatchDelete();">
                                        <input type="hidden" name="batch_delete" value="1">
                                        <div class="mb-3">
                                            <button type="submit" class="btn btn-danger" id="batch-kami-delete-btn">批量删除</button>
                                        </div>
                                        <!-- 移动端全选框，仅在小屏显示 -->
                                        <div class="d-block d-md-none mb-2">
                                            <label style="font-weight:bold;">
                                                <input type="checkbox" id="mobile-check-all-kami"> 全选
                                            </label>
                                        </div>
                                        <table class="table table-hover table-nowrap table-kami-mobile">
                                            <thead>
                                                <tr>
                                                    <th style="width:36px;"><input type="checkbox" id="check-all-kami"></th>
                                                    <th>卡密</th>
                                                    <th>类型</th>
                                                    <th>使用时间</th>
                                                    <th>到期时间</th>
                                                    <th>创建时间</th>
                                                    <th>生成方式</th>
                                                    <th>状态</th>
                                                    <th>操作</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (!empty($cards)): ?>
                                                    <?php foreach ($cards as $card): ?>
                                                    <tr>
                                                        <td><input type="checkbox" name="kami_ids[]" value="<?php echo $card['id']; ?>"></td>
                                                        <td><span class="kami-label">卡密</span><?php echo htmlspecialchars($card['kami_key']); ?>
                                                            <i class="mdi mdi-content-copy copy-btn" data-kami="<?php echo htmlspecialchars($card['kami_key']); ?>" title="复制卡密"></i>
                                                        </td>
                                                        <td><span class="kami-label">类型</span>
                                                            <?php 
                                                            // 从卡密生成时设置的值中提取时长
                                                            $duration = '';
                                                            $card_value = 0;
                                                            
                                                            if ($card['type'] == '永久卡') {
                                                                $duration = '永久';
                                                            } else {
                                                                // 提取时长值
                                                                switch ($card['type']) {
                                                                    case '分钟卡':
                                                                        if (!empty($card['expire_time']) && $card['expire_time'] !== '0000-00-00 00:00:00') {
                                                                            $card_value = ceil((strtotime($card['expire_time']) - strtotime($card['create_time'])) / 60);
                                                                            $duration = $card_value . '分钟';
                                                                        } else {
                                                                            $duration = '未设置';
                                                                        }
                                                                        break;
                                                                    case '小时卡':
                                                                        if (!empty($card['expire_time']) && $card['expire_time'] !== '0000-00-00 00:00:00') {
                                                                            $card_value = ceil((strtotime($card['expire_time']) - strtotime($card['create_time'])) / 3600);
                                                                            $duration = $card_value . '小时';
                                                                        } else {
                                                                            $duration = '未设置';
                                                                        }
                                                                        break;
                                                                    case '天卡':
                                                                        if (!empty($card['expire_time']) && $card['expire_time'] !== '0000-00-00 00:00:00') {
                                                                            $card_value = ceil((strtotime($card['expire_time']) - strtotime($card['create_time'])) / 86400);
                                                                            $duration = $card_value . '天';
                                                                        } else {
                                                                            $duration = '未设置';
                                                                        }
                                                                        break;
                                                                    case '周卡':
                                                                        if (!empty($card['expire_time']) && $card['expire_time'] !== '0000-00-00 00:00:00') {
                                                                            $card_value = ceil((strtotime($card['expire_time']) - strtotime($card['create_time'])) / (604800));
                                                                            $duration = $card_value . '周';
                                                                        } else {
                                                                            $duration = '未设置';
                                                                        }
                                                                        break;
                                                                    case '月卡':
                                                                        if (!empty($card['expire_time']) && $card['expire_time'] !== '0000-00-00 00:00:00') {
                                                                            $card_value = ceil((strtotime($card['expire_time']) - strtotime($card['create_time'])) / (2678400));
                                                                            $duration = $card_value . '个月';
                                                                        } else {
                                                                            $duration = '未设置';
                                                                        }
                                                                        break;
                                                                    case '季卡':
                                                                        if (!empty($card['expire_time']) && $card['expire_time'] !== '0000-00-00 00:00:00') {
                                                                            $card_value = ceil((strtotime($card['expire_time']) - strtotime($card['create_time'])) / (8035200));
                                                                            $duration = $card_value . '季';
                                                                        } else {
                                                                            $duration = '未设置';
                                                                        }
                                                                        break;
                                                                    case '年卡':
                                                                        if (!empty($card['expire_time']) && $card['expire_time'] !== '0000-00-00 00:00:00') {
                                                                            $card_value = ceil((strtotime($card['expire_time']) - strtotime($card['create_time'])) / (32140800));
                                                                            $duration = $card_value . '年';
                                                                        } else {
                                                                            $duration = '未设置';
                                                                        }
                                                                        break;
                                                                    default:
                                                                        $duration = '-';
                                                                }
                                                            }
                                                            
                                                            echo htmlspecialchars($card['type']) . ' <span style="color: red;">(' . $duration . ')</span>';
                                                            ?>
                                                        </td>
                                                        <td><span class="kami-label">使用时间</span>
                                                            <?php
                                                            if (!empty($card['first_use_time']) && $card['first_use_time'] !== '0000-00-00 00:00:00') {
                                                                echo htmlspecialchars($card['first_use_time']);
                                                            } else {
                                                                echo '<span class="text-muted">未激活</span>';
                                                            }
                                                            ?>
                                                        </td>
                                                        <td><span class="kami-label">到期时间</span>
                                                            <?php
                                                            if (!empty($card['first_use_time']) && $card['first_use_time'] !== '0000-00-00 00:00:00') {
                                                                $expire_time = null;
                                                                switch ($card['type']) {
                                                                    case '分钟卡': $expire_time = strtotime($card['first_use_time']) + 60; break;
                                                                    case '小时卡': $expire_time = strtotime($card['first_use_time']) + 3600; break;
                                                                    case '天卡': $expire_time = strtotime($card['first_use_time']) + 86400; break;
                                                                    case '周卡': $expire_time = strtotime($card['first_use_time']) + 604800; break;
                                                                    case '月卡': $expire_time = strtotime($card['first_use_time']) + 2592000; break;
                                                                    case '季卡': $expire_time = strtotime($card['first_use_time']) + 7776000; break;
                                                                    case '年卡': $expire_time = strtotime($card['first_use_time']) + 31536000; break;
                                                                    case '永久卡': $expire_time = null; break;
                                                                    default: $expire_time = null;
                                                                }
                                                                if ($expire_time) {
                                                                    echo '<span style="color:red;">' . date('Y-m-d H:i:s', $expire_time) . '</span>';
                                                                } else {
                                                                    echo '<span style="color:red;">永久</span>';
                                                                }
                                                            } else {
                                                                echo '<span class="text-muted">未激活</span>';
                                                            }
                                                            ?>
                                                        </td>
                                                        <td><span class="kami-label">创建时间</span><?php echo htmlspecialchars($card['create_time']); ?></td>
                                                        <td><span class="kami-label">生成方式</span>
                                                            <?php
                                                            if ($card['created_by'] == 0) {
                                                                echo '<span class="badge bg-primary">购买</span>';
                                                            } else if ($card['created_by'] == 1) {
                                                                echo '<span class="badge bg-danger">手动</span>';
                                                            } else {
                                                                echo '<span class="badge bg-secondary">-</span>';
                                                            }
                                                            ?>
                                                        </td>
                                                        <td><span class="kami-label">状态</span>
                                                            <?php
                                                            if ($card['status'] == 0) {
                                                                echo '<span class="badge bg-secondary">已禁用</span>';
                                                            } elseif (!empty($card['first_use_time']) && !empty($card['expire_time']) && $card['expire_time'] !== '0000-00-00 00:00:00' && strtotime($card['expire_time']) < time()) {
                                                                echo '<span class="badge bg-warning">已过期</span>';
                                                            } elseif ($card['use_count'] > 0) {
                                                                echo '<span class="badge bg-danger">已使用</span>';
                                                            } else {
                                                                echo '<span class="badge bg-success">未使用</span>';
                                                            }
                                                            ?>
                                                        </td>
                                                        <td class="kami-actions">
                                                            <div class="btn-group">
                                                                <!-- 启用/禁用按钮（放在最左边，带图标） -->
                                                                <button type="button" class="btn btn-xs <?php echo $card['status'] == 1 ? 'btn-warning' : 'btn-success'; ?>" onclick="toggleKamiStatus(<?php echo $card['id']; ?>)">
                                                                    <?php if ($card['status'] == 1): ?>
                                                                        <i class="mdi mdi-lock"></i> 禁用
                                                                    <?php else: ?>
                                                                        <i class="mdi mdi-lock-open"></i> 启用
                                                                    <?php endif; ?>
                                                                </button>
                                                                <!-- 删除按钮 -->
                                                                <button type="button" class="btn btn-xs btn-danger" onclick="deleteKami(<?php echo $card['id']; ?>)">
                                                                    <i class="mdi mdi-delete"></i> 删除
                                                                </button>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="10" class="text-center">暂无卡密记录</td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </form>
                                </div>
                                
                                <!-- 单行操作form写在批量form外部 -->
                                <?php if (!empty($cards)): ?>
                                    <?php foreach ($cards as $card): ?>
                                    <div style="display:none;">
                                        <form method="post" id="single-delete-<?php echo $card['id']; ?>">
                                            <input type="hidden" name="kami_id" value="<?php echo $card['id']; ?>">
                                            <input type="hidden" name="action" value="delete">
                                        </form>
                                        <form method="post" id="single-toggle-<?php echo $card['id']; ?>">
                                            <input type="hidden" name="kami_id" value="<?php echo $card['id']; ?>">
                                            <input type="hidden" name="action" value="toggle_status">
                                        </form>
                                    </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                                
                                <!-- 分页部分 -->
                                <?php if ($total_pages > 1): ?>
                                    <!-- 桌面端分页 -->
                                    <div class="d-none d-md-block">
                                        <ul class="pagination justify-content-center mt-3">
                                            <li class="page-item <?php if ($page <= 1) echo 'disabled'; ?>">
                                                <a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>&type_filter=<?php echo urlencode($type_filter); ?>" tabindex="-1" aria-disabled="true">上一页</a>
                                            </li>
                                            
                                            <?php
                                            $start_page = max(1, $page - 2);
                                            $end_page = min($total_pages, $page + 2);
                                            
                                            if ($start_page > 1) {
                                                echo '<li class="page-item"><a class="page-link" href="?page=1&search='.urlencode($search).'&status='.urlencode($status).'&type_filter='.urlencode($type_filter).'">1</a></li>';
                                                if ($start_page > 2) {
                                                    echo '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
                                                }
                                            }
                                            
                                            for ($i = $start_page; $i <= $end_page; $i++) {
                                                echo '<li class="page-item '.($i == $page ? 'active' : '').'"><a class="page-link" href="?page='.$i.'&search='.urlencode($search).'&status='.urlencode($status).'&type_filter='.urlencode($type_filter).'">'.$i.'</a></li>';
                                            }
                                            
                                            if ($end_page < $total_pages) {
                                                if ($end_page < $total_pages - 1) {
                                                    echo '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
                                                }
                                                echo '<li class="page-item"><a class="page-link" href="?page='.$total_pages.'&search='.urlencode($search).'&status='.urlencode($status).'&type_filter='.urlencode($type_filter).'">'.$total_pages.'</a></li>';
                                            }
                                            ?>
                                            
                                            <li class="page-item <?php if ($page >= $total_pages) echo 'disabled'; ?>">
                                                <a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>&type_filter=<?php echo urlencode($type_filter); ?>">下一页</a>
                                            </li>
                                        </ul>
                                    </div>
                                    
                                    <!-- 移动端分页 - 与桌面端相同的页码显示 -->
                                    <div class="d-block d-md-none">
                                        <style>
                                            /* 移动端分页样式优化 */
                                            @media (max-width: 767.98px) {
                                                .pagination-mobile .page-link {
                                                    padding: 0.25rem 0.5rem;
                                                    font-size: 0.875rem;
                                                }
                                            }
                                        </style>
                                        <ul class="pagination pagination-mobile justify-content-center mt-3">
                                            <li class="page-item <?php if ($page <= 1) echo 'disabled'; ?>">
                                                <a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>&type_filter=<?php echo urlencode($type_filter); ?>">
                                                    <i class="mdi mdi-chevron-left"></i>
                                                </a>
                                            </li>
                                            
                                            <?php
                                            // 移动端显示更少的页码，但保持与桌面端相同的逻辑
                                            $mobile_start = max(1, $page - 1);
                                            $mobile_end = min($total_pages, $page + 1);
                                            
                                            // 第一页
                                            if ($mobile_start > 1) {
                                                echo '<li class="page-item"><a class="page-link" href="?page=1&search='.urlencode($search).'&status='.urlencode($status).'&type_filter='.urlencode($type_filter).'">1</a></li>';
                                                if ($mobile_start > 2) {
                                                    echo '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
                                                }
                                            }
                                            
                                            // 当前页附近的页码
                                            for ($i = $mobile_start; $i <= $mobile_end; $i++) {
                                                echo '<li class="page-item '.($i == $page ? 'active' : '').'"><a class="page-link" href="?page='.$i.'&search='.urlencode($search).'&status='.urlencode($status).'&type_filter='.urlencode($type_filter).'">'.$i.'</a></li>';
                                            }
                                            
                                            // 最后一页
                                            if ($mobile_end < $total_pages) {
                                                if ($mobile_end < $total_pages - 1) {
                                                    echo '<li class="page-item disabled"><a class="page-link" href="#">...</a></li>';
                                                }
                                                echo '<li class="page-item"><a class="page-link" href="?page='.$total_pages.'&search='.urlencode($search).'&status='.urlencode($status).'&type_filter='.urlencode($type_filter).'">'.$total_pages.'</a></li>';
                                            }
                                            ?>
                                            
                                            <li class="page-item <?php if ($page >= $total_pages) echo 'disabled'; ?>">
                                                <a class="page-link" href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>&type_filter=<?php echo urlencode($type_filter); ?>">
                                                    <i class="mdi mdi-chevron-right"></i>
                                                </a>
                                            </li>
                                        </ul>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="mt-3">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="alert alert-info">
                                                <p>总共 <strong><?php echo $total; ?></strong> 条记录，当前显示第 <strong><?php echo $page; ?></strong> 页，共 <strong><?php echo $total_pages; ?></strong> 页</p>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="alert alert-primary">
                                                <p>提示：可以通过搜索框搜索卡密，也可以通过状态和类型进行筛选。</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
        <!--End 页面主要内容-->
    </div>
</div>

<script type="text/javascript" src="../assets/js/jquery.min.js"></script>
<script type="text/javascript" src="../assets/js/popper.min.js"></script>
<script type="text/javascript" src="../assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../assets/js/perfect-scrollbar.min.js"></script>
<script type="text/javascript" src="../assets/js/jquery.mCustomScrollbar.concat.min.js"></script>
<script type="text/javascript" src="../assets/js/bootstrap-notify.min.js"></script>
<script type="text/javascript" src="../assets/js/main.min.js"></script>
<script>
$(document).ready(function() {
    // 检测是否为移动设备
    var isMobile = window.matchMedia("only screen and (max-width: 767.98px)").matches;
    
    // 移动端表格优化
    if (isMobile) {
        // 为表格添加小尺寸类
        $('.table').addClass('table-sm');
        
        // 添加表格滚动提示
        $('.table-responsive').each(function() {
            if ($(this).find('table').width() > $(this).width()) {
                var $scrollHint = $('<div class="text-muted text-center mt-2 mb-2"><small><i class="mdi mdi-gesture-swipe"></i> 左右滑动查看更多</small></div>');
                $(this).before($scrollHint);
                
                // 3秒后淡出提示
                setTimeout(function() {
                    $scrollHint.fadeOut(1000);
                }, 3000);
            }
        });
    }
    
    // 复制卡密功能（支持操作列按钮）
    $(document).on('click', '.copy-btn', function() {
        var kami = $(this).data('kami');
        var tempInput = $('<input>');
        $('body').append(tempInput);
        tempInput.val(kami).select();
        document.execCommand('copy');
        tempInput.remove();
        $.notify({
            message: '卡密已复制到剪贴板'
        },{
            type: 'success',
            placement: { from: 'top', align: 'center' },
            z_index: 10800,
            delay: 1500,
            animate: { enter: 'animate__animated animate__fadeInDown', exit: 'animate__animated animate__fadeOutUp' }
        });
    });

    // 全选/反选
    $(document).off('change', '#check-all-kami').on('change', '#check-all-kami', function() {
        var checked = $(this).prop('checked');
        $('input[name="kami_ids[]"]').prop('checked', checked);
    });

    // 移动端全选功能
    $(document).on('change', '#mobile-check-all-kami', function() {
        var checked = $(this).prop('checked');
        $('input[name="kami_ids[]"]').prop('checked', checked);
        $('#check-all-kami').prop('checked', checked); // 同步桌面端全选
    });
    // 其它checkbox变动时，同步移动端全选框状态
    $(document).on('change', 'input[name="kami_ids[]"]', function() {
        var all = $('input[name="kami_ids[]"]').length;
        var checked = $('input[name="kami_ids[]"]:checked').length;
        $('#mobile-check-all-kami').prop('checked', all === checked);
        $('#check-all-kami').prop('checked', all === checked);
    });
});
// 全局作用域：单行操作按钮触发隐藏form提交
function deleteKami(id) {
    if (confirm('确定要删除此卡密吗？此操作不可恢复！')) {
        document.getElementById('single-delete-' + id).submit();
    }
}
function toggleKamiStatus(id) {
    document.getElementById('single-toggle-' + id).submit();
}
// 新增表单校验函数
function checkBatchDelete() {
    var checked = $('input[name="kami_ids[]"]:checked').length;
    if (checked === 0) {
        alert('请先选择要删除的卡密！');
        return false;
    }
    return confirm('确定要删除选中的卡密吗？此操作不可恢复！');
}
</script>
</body>
</html> 